package com.ljy.iecasbasedemo.viewModel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import org.unicorn.android.base.BaseViewModel
import org.unicorn.android.base.network
import org.unicorn.android.base.toast
import com.ljy.iecasbasedemo.bean.TestBean
import com.ljy.iecasbasedemo.repository.MainRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext

/**
 *
 * @author     : liujianyou
 * @date : 2022/02/17 09:00
 * @Description:
 */
class MainViewModel : BaseViewModel() {

    private val mainRepository by lazy { MainRepository() }

    val testLiveData: MutableLiveData<TestBean> = MutableLiveData()

    val testFlow = MutableSharedFlow<TestBean>()
    val testFlow1 = MutableSharedFlow<TestBean>()

    fun requestApi() {
        network({
            flow {
                Log.d("BuildF", "flow: "+Thread.currentThread().name)
                mainRepository.requestApi()?.let { this.emit(it) }
            }.flowOn(Dispatchers.IO).collect {
                Log.d("BuildF", "collect: $it" +Thread.currentThread().name)
                withContext(Dispatchers.Main) {
                    testFlow.emit(it)
                    testFlow1.emit(it)
                }
            }
            val requestApi = mainRepository.requestApi()
            if (requestApi != null) {
                testLiveData.postValue(requestApi!!)
            }
        }, onError = { code, msg ->
            toast(msg)
        })
    }

}